<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Infotech Ltd.
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2007/02/28 20:11:57 $)
// $RCSfile: functions_followup.php,v $ : $Revision: 1.7 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/*
	$_SWIFT["query"]["create"]["ticketfollowup"] = "CREATE TABLE ". TABLE_PREFIX ."ticketfollowup (
																		ticketfollowupid INT UNSIGNED NOT NULL AUTO_INCREMENT,
																		dateline INT UNSIGNED NOT NULL DEFAULT '0',
																		execdateline INT UNSIGNED NOT NULL DEFAULT '0',
																		ticketid INT UNSIGNED NOT NULL DEFAULT '0',
																		staffid INT UNSIGNED NOT NULL DEFAULT '0',
																		ownerstaffid INT UNSIGNED NOT NULL DEFAULT '0',
																		departmentid INT UNSIGNED NOT NULL DEFAULT '0',
																		ticketstatusid INT UNSIGNED NOT NULL DEFAULT '0',
																		priorityid INT UNSIGNED NOT NULL DEFAULT '0',
																		duedateline INT UNSIGNED NOT NULL DEFAULT '0',
																		timeworked INT UNSIGNED NOT NULL DEFAULT '0',
																		donote SMALLINT(1) UNSIGNED NOT NULL DEFAULT '0',
																		notetype SMALLINT(1) UNSIGNED NOT NULL DEFAULT '0',
																		ticketnotes MEDIUMTEXT NOT NULL DEFAULT '',
																		doreply SMALLINT(1) UNSIGNED NOT NULL DEFAULT '0',
																		replycontents MEDIUMTEXT NOT NULL DEFAULT '',
																		doforward SMALLINT(1) UNSIGNED NOT NULL DEFAULT '0',
																		forwardcontents MEDIUMTEXT NOT NULL DEFAULT '',
																		PRIMARY KEY (ticketfollowupid),
																		KEY ticketfollowup1 (ticketid),
																		KEY ticketfollowup2 (execdateline)
																	);";
*/

/**
* Processes the pending follow ups
*/
function processPendingFollowUps()
{
	global $dbCore, $_SWIFT;

	$_ticketfollowupidlist = $_ticketobjlist = $_departmentidlist = $_followuplist = array();
	$index = 0;

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."ticketfollowup` WHERE `execdateline` <= '". DATENOW ."';");
	while ($dbCore->nextRecord())
	{
		$_followuplist[$dbCore->Record["ticketfollowupid"]] = $dbCore->Record;
		$_ticketfollowupidlist[] = $dbCore->Record["ticketfollowupid"];
	}

	if (count($_ticketfollowupidlist))
	{
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."ticketfollowup` WHERE `ticketfollowupid` IN (". buildIN($_ticketfollowupidlist) .");");
	}


	foreach ($_followuplist as $key=>$val)
	{
		$_ticketfollowupidlist[] = $val["ticketfollowupid"];
		$_ticketobjlist[$index] =& new TicketMain($val["ticketid"], false, LOG_SYSTEM);
		$_ticketobj = &$_ticketobjlist[$index];
		$_ticketobj->norecount = true;
		$_SWIFT["staff"] = $_SWIFT["staffcache"][$val["staffid"]];

		// Do we need to add this department to recount list?
		if (!empty($val["departmentid"]))
		{
			if (!in_array($val["departmentid"], $_departmentidlist))
			{
				$_departmentidlist[] = $val["departmentid"];
			}

			if (!in_array($_ticketobj->ticket["departmentid"], $_departmentidlist))
			{
				$_departmentidlist[] = $_ticketobj->ticket["departmentid"];
			}
		}

		// Do we need to recount the department due to status change?
		if (!empty($val["ticketstatusid"]))
		{
			if (!in_array($_ticketobj->ticket["departmentid"], $_departmentidlist))
			{
				$_departmentidlist[] = $_ticketobj->ticket["departmentid"];
			}
		}

		// ======= !! PROCESS REQUIRED ACTIONS !! =======

		// Change Owner?
		if (!empty($val["ownerstaffid"]) && $val["ownerstaffid"] != -1)
		{
			$_ticketobj->assignTicket($val["ownerstaffid"]);
		}

		// Change Department?
		if (!empty($val["departmentid"]) && $val["departmentid"] != -1)
		{
			$_ticketobj->moveTicket($val["departmentid"]);
		}

		// Change Status?
		if (!empty($val["ticketstatusid"]) && $val["ticketstatusid"] != -1)
		{
			$_ticketobj->changeStatus($val["ticketstatusid"]);
		}

		// Change Priority?
		if (!empty($val["priorityid"]) && $val["priorityid"] != -1)
		{
			$_ticketobj->changePriority($val["priorityid"]);
		}

		// Due Date?
		if (!empty($val["duedateline"]) && $val["duedateline"] != -1)
		{
			$_ticketobj->markAsDue($val["duedateline"]);
		} else if ($val["markasoverdue"] == 1) {
			$_ticketobj->markAsDue();
		}

		// Time Worked
		if (!empty($val["timeworked"]) && $val["timeworked"] != -1)
		{
			$_ticketobj->addTimeWorked($val["timeworked"]);
		}

		// Add a Note?
		if ($val["donote"] == 1)
		{
			$_ticketobj->addTicketNote(iif(empty($val["notetype"]), NOTE_TICKET, $val["notetype"]), 0, $val["ticketnotes"]);
		}

		// Send a Reply?
		if ($val["doreply"] == 1)
		{
			$staffsignature = $_SWIFT["staff"]["signature"];
			$_ticketobj->createStaffReply($val["staffid"], $_SWIFT["staffcache"][$val["staffid"]]["fullname"], $_SWIFT["staffcache"][$val["staffid"]]["email"], $_ticketobj->ticket["subject"], $val["replycontents"].iif(!empty($staffsignature), SWIFT_CRLF.$staffsignature), 0, $_ticketobj->ticket["emailqueueid"], false, '', false, '', false, false, false);
		}

		// Forward Ticket?
		if ($val["doforward"] == 1)
		{
			$_ticketobj->forwardTicket($val["staffid"], $_SWIFT["staffcache"][$val["staffid"]]["fullname"], $_SWIFT["staffcache"][$val["staffid"]]["email"], $val["forwardemailto"], $_ticketobj->ticket["subject"], $val["forwardcontents"], 0, false, false, array());
		}

		$_ticketobj->recountTicketFollowUps();

		$index++;
	}

	if (count($_departmentidlist))
	{
		$_SWIFT["recountdep"] = $_departmentidlist;
		register_shutdown_function("recountTicketDepartments");
	}

	return true;
}



/**
* Generates a Random ID
*/
function generateRandomID()
{
	srand((double)microtime()*10000000);
	$id = base_convert(time(), 10, 36).".". base_convert(rand(), 10, 36);
	return $id;
}

/**
* Renders the Tab Contents of Follow-Up tab
*/
function renderFollowUpTabContents(&$_ticketobj, $noform = false, $nomenus = false)
{
	global $dbCore, $_SWIFT;

	$_ticket = &$_ticketobj->ticket;
	extract(generateTicketSelectBoxes($_ticket, 'fu'));

	$_random = generateRandomID();

	if (!$noform)
	{
		printFormStart("followupform", "index.php", "POST", false, "", "javascript:return processFollowUpForm('". addslashes($_SWIFT["language"]["followupformerror"]) ."');");
		echo '<table border="0" cellpadding="3" cellspacing="1" width="100%" class="tborder">'.SWIFT_CRLF;
	} else {
		echo '<table border="0" cellpadding="3" cellspacing="1" width="100%">'.SWIFT_CRLF;
	}

	echo '<tr class="'. getRowBG() .'">
	<td width="100" align="left"><span class="tabletitle"><select class="swiftselect" name="followuptype" onChange="javascript:followupTrigger(this.options[this.selectedIndex].value, '. intval($noform) .');">
	<option value="minutes">In X Minutes</option>
	<option value="hours">In X Hours</option>
	<option value="days">In X Days</option>
	<option value="weeks">In X Weeks</option>
	<option value="months">In X Months</option>
	<option value="custom">Custom</option>
	</select></span></td>
	<td align="left" class="smalltext"><div id="fuvalblock"><input type="text" name="followupvalue" class="swifttext" id="followupvalue" value="" size="4" /></div><div id="fucalblock" style="DISPLAY: none;"><input type="text" name="followupcalvalue" id="followupcalvalue" onclick="return showCalendar(\'followupcalvalue\', \''. iif($_SWIFT["settings"]["dt_caltype"]=="us", "%m/%d/%Y", "%d/%m/%Y") .'\');" size="12" readonly="1" value="" class="swifttext"/>&nbsp;<img src="'. $_SWIFT["themepath"] .'calendar.gif" id="opt_rduet" onclick="return showCalendar(\'followupcalvalue\', \''. iif($_SWIFT["settings"]["dt_caltype"]=="us", "%m/%d/%Y", "%d/%m/%Y") .'\');" style="cursor: pointer;" align="absmiddle"/></div>
	</td>
	</tr>';

	echo '<tr onclick="">
<td class="followuptitlerow" title="" onmouseover="this.className=\'followuptitlerowhover\';" onmouseout="this.className=\'followuptitlerow\';" align="left" valign="top" colspan="2" width=""><label for="fugeneral"><input type="checkbox" onclick="javascript:followupHandleItems(\'general\');this.blur();" name="fugeneral" id="fugeneral" value="1" style="margin: 0px; padding: 0px;" /> '. $_SWIFT["language"]["tabgeneral"] .'</label></td>
</tr>';

	echo '<tr onclick="" id="fumgeneral" style="display:none;">
<td class="row1" title="" align="left" valign="top" colspan="2" width=""><table border="0" cellpadding="3" cellspacing="1" width="100%" class="tborder">';

	echo '<tr class="tabletitlerow"><td width="15%" align="center">'. $_SWIFT["language"]["f_owner"] .'</td><td width="15%" align="center">'. $_SWIFT["language"]["f_department"] .'</td><td width="15%" align="center">'. $_SWIFT["language"]["f_ticketstatus"] .'</td><td width="15%" align="center">'. $_SWIFT["language"]["f_priority"] .'</td><td width="15%" align="center">'. $_SWIFT["language"]["f_duedate"] .'</td></tr>';
	echo '<tr><td align="center">'. $_staffselect .'</td><td align="center">'. $_departmentselect .'</td><td align="center">'. $_statusselect .'</td><td align="center">'. $_priorityselect .'</td><td align="center"><input type="text" name="fuopt_due" id="fuopt_due'.$_random.'" size="12" readonly="1" value="'. iif($_ticket["duetime"]!="0", generateCalendarTimeline($_ticket["duetime"])) .'" class="swifttext" onclick="return showCalendar(\'fuopt_due'.$_random.'\', \''. iif($_SWIFT["settings"]["dt_caltype"]=="us", "%m/%d/%Y", "%d/%m/%Y") .'\');" />&nbsp;<img src="'. $_SWIFT["themepath"] .'calendar.gif" id="opt_duetrigger" style="cursor: pointer;" title="'. $title .'" align="absmiddle" onclick="return showCalendar(\'fuopt_due'.$_random.'\', \''. iif($_SWIFT["settings"]["dt_caltype"]=="us", "%m/%d/%Y", "%d/%m/%Y") .'\');" /></td></tr>';
	echo '</table></td>
</tr>';



	echo '<tr onclick="">
<td class="followuptitlerow" title="" onmouseover="this.className=\'followuptitlerowhover\';" onmouseout="this.className=\'followuptitlerow\';" align="left" valign="top" colspan="2" width=""><label for="fuaddnotes"><input type="checkbox" name="fuaddnotes" onclick="javascript:followupHandleItems(\'addnotes\');this.blur();" id="fuaddnotes" value="1" style="margin: 0px; padding: 0px;" /> '. $_SWIFT["language"]["tabaddnotes"] .'</label></td>
</tr>';

	echo '<tr onclick="" id="fumaddnotes" style="display:none;">
<td class="row1" title="" align="left" valign="top" colspan="2" width=""><table border="0" cellpadding="3" cellspacing="1" width="100%" class="tborder">';

	printDescRow($_SWIFT["language"]["noteoptions"]);
	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["ticket"];
	$options[0]["value"] = NOTE_TICKET;
	$options[0]["checked"] = true;
	$options[1]["title"] = $_SWIFT["language"]["user"];
	$options[1]["value"] =NOTE_USER;
	printRadioRow("funotetype", $_SWIFT["language"]["notetype"], "", $options, "", true);
	printDescRow($_SWIFT["language"]["contents"]);
	$colarray = array();
	$colarray[0]["align"] = "left";
	$colarray[0]["valign"] = "top";
	$colarray[0]["colspan"] = "2";
	$colarray[0]["nowrap"] = true;
	$colarray[0]["value"] = '<textarea style="WIDTH:100%;" name="funotecontents" cols="100" rows="3">'. htmlspecialchars($_POST["notecontents"]) .'</textarea>'.SWIFT_CRLF;
	$colarray[0]["class"] = getRowBG();
	printDataRow($colarray);
	echo '</table></td>
</tr>';

	
	echo '<tr onclick="">
<td class="followuptitlerow" title="" onmouseover="this.className=\'followuptitlerowhover\';" onmouseout="this.className=\'followuptitlerow\';" align="left" valign="top" colspan="2" width=""><label for="fupostreply"><input type="checkbox" onclick="javascript:followupHandleItems(\'postreply\');this.blur();" name="fupostreply" id="fupostreply" value="1" style="margin: 0px; padding: 0px;" /> '. $_SWIFT["language"]["tabpostreply"] .'</label></td>
</tr>';

	echo '<tr onclick="" id="fumpostreply" style="display:none;">
<td class="row1" title="" align="left" valign="top" colspan="2" width=""><table border="0" cellpadding="3" cellspacing="1" width="100%" class="tborder">';

if (!$nomenus)
{
	echo '<tr class="'. getRowBG() .'">
	<td width="100" align="left" id="fumenuref'.$_random.'"><span class="tabletitle">'. $_SWIFT["language"]["quickinsert"] .'</span></td>
	<td align="left"><a href="#" title="'. $_SWIFT["qquote"] .'" id="fuquotelink'.$_random.'" onClick="javascript:CustomPopupRef(\'fwquotemenu\', event, \'fuquotelink'.$_random.'\', \'fwquotemenu\', \'fumenuref'.$_random.'\', true);this.blur();" onMouseUp="javascript:this.blur();"><img src="'. $_SWIFT["themepath"] .'icon_quotedrop.gif" border="0" align="absmiddle" />&nbsp;'. $_SWIFT["language"]["qquote"] .'&nbsp;<img src="'. $_SWIFT["themepath"] .'menudrop.gif" border="0" align="absmiddle" /></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" title="'. $_SWIFT["qpredefinedreplies"] .'" id="fuprcachelink'.$_random.'" onClick="javascript:CustomPopupRef(\'prcachemenu\', event, \'fuprcachelink'.$_random.'\', \'prcachemenu\', \'fumenuref'.$_random.'\', prmenuloaded);this.blur();" onMouseUp="javascript:this.blur();"><img src="'. $_SWIFT["themepath"] .'icon_quickinsert.gif" border="0" align="absmiddle" />&nbsp;'. $_SWIFT["language"]["qpredefinedreplies"] .'&nbsp;<img src="'. $_SWIFT["themepath"] .'menudrop.gif" border="0" align="absmiddle" /></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" title="'. $_SWIFT["qknowledgebase"] .'" id="fukbcachelink'.$_random.'" onClick="javascript:CustomPopupRef(\'kbcachemenu\', event, \'fukbcachelink'.$_random.'\', \'fukbcachemenu\', \'fumenuref'.$_random.'\', kbmenuloaded);this.blur();" onMouseUp="javascript:this.blur();"><img src="'. $_SWIFT["themepath"] .'icon_quickinsert.gif" border="0" align="absmiddle" />&nbsp;'. $_SWIFT["language"]["qknowledgebase"] .'&nbsp;<img src="'. $_SWIFT["themepath"] .'menudrop.gif" border="0" align="absmiddle" /></a></td>
	</tr>';
}
	printDescRow($_SWIFT["language"]["contents"]);
	$colarray = array();
	$colarray[0]["align"] = "left";
	$colarray[0]["valign"] = "top";
	$colarray[0]["colspan"] = "2";
	$colarray[0]["nowrap"] = true;
	$colarray[0]["value"] = '<textarea style="WIDTH:100%;" name="fureplycontents" cols="100" rows="15" tabindex="99" onselect="javascript:storeCaret(this);" onclick="javascript:storeCaret(this);" onkeyup="javascript:storeCaret(this);">'. htmlspecialchars(iif(!empty($_ticket["draft"]), $_ticket["draft"], $_POST["replycontents"])) .'</textarea>'.SWIFT_CRLF;
	$colarray[0]["class"] = getRowBG();
	printDataRow($colarray);


	echo '</table></td>
</tr>';


	echo '<tr onclick="">
<td class="followuptitlerow" title="" onmouseover="this.className=\'followuptitlerowhover\';" onmouseout="this.className=\'followuptitlerow\';" align="left" valign="top" colspan="2" width=""><label for="fuforward"><input type="checkbox" onclick="javascript:followupHandleItems(\'forward\');this.blur();" name="fuforward" id="fuforward" value="1" style="margin: 0px; padding: 0px;" /> '. $_SWIFT["language"]["tabforward"] .'</label></td>
</tr>';

	echo '<tr onclick="" id="fumforward" style="display:none;">
<td class="row1" title="" align="left" valign="top" colspan="2" width=""><table border="0" cellpadding="3" cellspacing="1" width="100%" class="tborder">';

	echo '<tr class="'. getRowBG() .'">
	<td width="100" align="left"><span class="tabletitle">'. $_SWIFT["language"]["to"] .'</span></td>
	<td align="left"><input type="text" size="40" name="fuopt_to" value="" class="swifttext">&nbsp;&nbsp;<a href="javascript:popupInfoWindow(\''. $_SWIFT["swiftpath"] .'staff/index.php?_m=core&_a=userlookup&formname=followupform&formfield=opt_to&sessionid='. $_SWIFT["session"]["sessionid"] .'\');"><img src="'. $_SWIFT["themepath"] .'icon_searchlookup.gif" title="'. $_SWIFT["language"]["lookup"] .'" border="0" align="absmiddle" /></a></td></tr>';

	printDescRow($_SWIFT["language"]["contents"]);
	$colarray = array();
	$colarray[0]["align"] = "left";
	$colarray[0]["valign"] = "top";
	$colarray[0]["colspan"] = "2";
	$colarray[0]["nowrap"] = true;
	$colarray[0]["value"] = '<textarea style="WIDTH:100%;" name="fuforwardcontents" cols="100" rows="15" tabindex="99" onselect="javascript:storeCaret(this);" onclick="javascript:storeCaret(this);" onkeyup="javascript:storeCaret(this);">'. htmlspecialchars(iif(!empty($_ticket["draft"]), $_ticket["draft"], $_POST["replycontents"])) .'</textarea>'.SWIFT_CRLF;
	$colarray[0]["class"] = getRowBG();
	printDataRow($colarray);


	echo '</table></td>
</tr>';



	if (!$noform)
	{

	$data[0]["value"] = '<input type="submit" class="yellowbuttonbig" value="'. $_SWIFT["language"]["submit"] .'" />'.SWIFT_CRLF;
	$data[0]["align"] = "left";
	$data[0]["colspan"] = 2;
	printDataRow($data);

	echo '</table><BR /> ';
	addHiddenField("_m", "tickets");
		addHiddenField("_a", "ticketactions");
		addHiddenField("dofollowup", "1");
		addHiddenField("action", "followup");
		addHiddenField("ticketlabelid", $_REQUEST["ticketlabelid"]);
		addHiddenField("ticketid", $_ticket["ticketid"]);
		printFormEnd();
	} else {
	echo '</table><BR /> ';
		addHiddenField("dofollowup", "1");
	}
}


/**
* Parse the followup data from $_POST
*/
function parseFollowUp(&$_ticketobj)
{
	global $dbCore, $_SWIFT;

	if (!is_object($_ticketobj) || ($_POST["followuptype"] != "custom" && empty($_POST["followupvalue"])) || ($_POST["followuptype"] == "custom" && empty($_POST["followupcalvalue"])))
	{
		return false;
	}

	$_execdateline = returnFollowUpDate($_POST["followuptype"], iif($_POST["followuptype"]=="custom", $_POST["followupcalvalue"], $_POST["followupvalue"]));
	if (!$_execdateline)
	{
		return false;
	}

	// Lets start with General section
	if ($_POST["fugeneral"] == 1)
	{
		$_ownerstaffid = intval($_POST["futt_staffid"]);
		$_departmentid = intval($_POST["futt_departmentid"]);
		$_ticketstatusid = intval($_POST["futt_ticketstatusid"]);
		$_priorityid = intval($_POST["futt_priorityid"]);
		if (empty($_duedateline))
		{
			$_duedateline = -1;
		} else {
			$_duedateline = intval(getCalendarDateline($_POST["fu_optdue"]));
		}
	}

	// Parse the Notes Section
	if ($_POST["fuaddnotes"] == 1)
	{
		$_donote = 1;
		$_notetype = intval($_POST["funotetype"]);
		$_notecontents = $_POST["funotecontents"];
	}

	// Post Reply Section
	if ($_POST["fupostreply"] == 1)
	{
		$_doreply = 1;
		$_replycontents = $_POST["fureplycontents"];
	}

	// Forward Section
	if ($_POST["fuforward"] == 1 && !empty($_POST["fuopt_to"]))
	{
		$_doforward = 1;
		$_forwardemailto = $_POST["fuopt_to"];
		$_forwardcontents = $_POST["fuforwardcontents"];
	}

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."ticketfollowup` (`dateline`, `execdateline`, `ticketid`, `staffid`, `ownerstaffid`, `departmentid`, `ticketstatusid`, `priorityid`, `duedateline`, `markasoverdue`, `timeworked`, `donote`, `notetype`, `ticketnotes`, `doreply`, `replycontents`, `doforward`, `forwardemailto`, `forwardcontents`) VALUES ('". DATENOW ."', '". intval($_execdateline) ."', '". intval($_ticketobj->ticket["ticketid"]) ."', '". intval($_SWIFT["staff"]["staffid"]) ."', '". intval($_ownerstaffid) ."', '". intval($_departmentid) ."', '". intval($_ticketstatusid) ."', '". intval($_priorityid) ."', '". intval($_duedateline) ."', '0', '0', '". intval($_donote) ."', '". intval($_notetype) ."', '". $dbCore->escape($_notecontents) ."', '". intval($_doreply) ."', '". $dbCore->escape($_replycontents) ."', '". intval($_doforward) ."', '". $dbCore->escape($_forwardemailto) ."', '". $dbCore->escape($_forwardcontents) ."')");

	return true;
}

/**
* Gets the follow up date
*/
function returnFollowUpDate($followuptype, $followupvalue)
{
	switch ($followuptype)
	{
		case 'minutes':
			return DATENOW+(intval($followupvalue)*60);
			break;
		case 'hours':
			return DATENOW+(intval($followupvalue)*60*60);
			break;
		case 'days':
			return DATENOW+(intval($followupvalue)*60*60*24);
			break;
		case 'weeks':
			return DATENOW+(intval($followupvalue)*60*60*24*7);
			break;
		case 'months':
			return DATENOW+(intval($followupvalue)*60*60*24*30);
			break;
		case 'custom':
			return getCalendarDateline($followupvalue);
			break;
		default:
			return false;
			break;
	}

	return false;
}

?>